<template>
  <div class="container fade-in">
    <div class="header">
      <h2 class="section-title">商户详情</h2>
      <div class="actions">
        <router-link to="/merchants" class="btn secondary">返回列表</router-link>
      </div>
  </div>

    <div class="card slide-up" style="animation-delay: 0.2s">
      <div v-if="loading" class="loading-state">
        <div class="loading-spinner"></div>
        <p>加载中...</p>
      </div>
      <div v-else-if="!merchant" class="empty-state">
        <div class="icon">❓</div>
        <h3>未找到该商户</h3>
        <p>请返回列表重新选择</p>
      </div>
      <div v-else class="detail-grid">
        <div class="row"><div class="label">商户编码</div><div class="value">{{ merchant.merchantCode || '-' }}</div></div>
        <div class="row"><div class="label">名称</div><div class="value">{{ merchant.name }}</div></div>
        <div class="row"><div class="label">联系人</div><div class="value">{{ merchant.contactPerson || '-' }}</div></div>
        <div class="row"><div class="label">联系电话</div><div class="value">{{ merchant.contactPhone || '-' }}</div></div>
        <div class="row"><div class="label">地址</div><div class="value">{{ merchant.address || '-' }}</div></div>
        <div class="row"><div class="label">详细地址</div><div class="value">{{ merchant.detailedAddress || '-' }}</div></div>
        <div class="row"><div class="label">审核状态</div><div class="value">{{ auditText(merchant.auditStatus) }}</div></div>
        <div class="row"><div class="label">账户状态</div><div class="value">{{ accountText(merchant.accountStatus) }}</div></div>
        <div class="row"><div class="label">创建时间</div><div class="value">{{ formatDate(merchant.creationTime) }}</div></div>
      </div>
    </div>

    <!-- 商户进件资料（基于后端 GetMerchantEntryDetailAsync 接口） -->
    <div class="card slide-up" style="animation-delay: 0.25s" v-if="merchant">
      <div class="card-header">
        <h3>商户进件资料</h3>
        <div class="card-subtitle">展示收单信息与进件材料（JSON 资料）</div>
      </div>

      <div v-if="entryLoading" class="loading-state">
        <div class="loading-spinner"></div>
        <p>进件资料加载中...</p>
      </div>
      <div v-else-if="!entry" class="empty-state">
        <div class="icon">📄</div>
        <h3>暂无进件资料</h3>
        <p>可尝试刷新或稍后重试</p>
      </div>
      <div v-else class="detail-grid">
        <div class="row"><div class="label">进件名称</div><div class="value">{{ entry.merchantName || '-' }}</div></div>
        <div class="row"><div class="label">收单机构 SPID</div><div class="value">{{ entry.acqSpId || '-' }}</div></div>
        <div class="row"><div class="label">收单商户号</div><div class="value">{{ entry.acqMerId || entry.merId || '-' }}</div></div>
        <div class="row"><div class="label">接单能力</div><div class="value">{{ acceptOrderText(entry.acceptOrder) }}</div></div>
        <div class="row"><div class="label">进件审核说明</div><div class="value">{{ entry.auditMsg || '-' }}</div></div>
        <div class="row"><div class="label">进件审核时间</div><div class="value">{{ formatDate(entry.auditTime) }}</div></div>
      </div>

      <!-- 进件材料（paper）结构化展示 -->
      <div v-if="entry?.paper" class="subcards">
        <div class="subcard">
          <h4 class="subcard-title">基本信息</h4>
          <div class="detail-grid">
            <div class="row"><div class="label">商户简称</div><div class="value">{{ entry.paper.ShortName || '-' }}</div></div>
            <div class="row"><div class="label">商户类型</div><div class="value">{{ entry.paper.MerchantType || '-' }}</div></div>
            <div class="row"><div class="label">是否个体户</div><div class="value">{{ formatYesNo(entry.paper.SoleInvestor) }}</div></div>
          </div>
        </div>

        <div v-if="entry.paper.ContactInfo" class="subcard">
          <h4 class="subcard-title">联系人信息</h4>
          <div class="detail-grid">
            <div class="row"><div class="label">联系人</div><div class="value">{{ entry.paper.ContactInfo?.ContactPerson || '-' }}</div></div>
            <div class="row"><div class="label">手机</div><div class="value">{{ entry.paper.ContactInfo?.ContactPhone || '-' }}</div></div>
            <div class="row"><div class="label">邮箱</div><div class="value">{{ entry.paper.ContactInfo?.Email || '-' }}</div></div>
            <div class="row"><div class="label">身份类型</div><div class="value">{{ entry.paper.ContactInfo?.ContactType || '-' }}</div></div>
            <div class="row"><div class="label">证件类型</div><div class="value">{{ entry.paper.ContactInfo?.ContactCertType || '-' }}</div></div>
            <div class="row"><div class="label">证件号码</div><div class="value">{{ entry.paper.ContactInfo?.ContactCertNo || '-' }}</div></div>
            <div class="row"><div class="label">证件有效期</div><div class="value">{{ entry.paper.ContactInfo?.ContactCertFrom || '-' }} ~ {{ entry.paper.ContactInfo?.ContactCertTo || '-' }}</div></div>
          </div>
          <div class="thumbs">
            <div v-if="entry.paper.ContactInfo?.ContactPhotoFrontURL" class="thumb"><img :src="safeUrl(entry.paper.ContactInfo?.ContactPhotoFrontURL)" alt="身份证正面"></div>
            <div v-if="entry.paper.ContactInfo?.ContactPhotoBackURL" class="thumb"><img :src="safeUrl(entry.paper.ContactInfo?.ContactPhotoBackURL)" alt="身份证反面"></div>
            <div v-if="entry.paper.ContactInfo?.ContactBusinessAuthURL" class="thumb"><img :src="safeUrl(entry.paper.ContactInfo?.ContactBusinessAuthURL)" alt="授权函"></div>
          </div>
        </div>

        <div v-if="entry.paper.CompanyInfo" class="subcard">
          <h4 class="subcard-title">经营信息</h4>
          <div class="detail-grid">
            <div class="row"><div class="label">省市区</div><div class="value">{{ [entry.paper.CompanyInfo?.Province, entry.paper.CompanyInfo?.City, entry.paper.CompanyInfo?.Area].filter(Boolean).join(' / ') || '-' }}</div></div>
            <div class="row"><div class="label">经营地址</div><div class="value">{{ entry.paper.CompanyInfo?.BusinessAddress || '-' }}</div></div>
            <div class="row"><div class="label">MCC</div><div class="value">{{ entry.paper.CompanyInfo?.Mcc || '-' }}</div></div>
            <div class="row"><div class="label">营业执照类型</div><div class="value">{{ entry.paper.CompanyInfo?.BusinessLicenseType || '-' }}</div></div>
            <div class="row"><div class="label">统一社会信用代码</div><div class="value">{{ entry.paper.CompanyInfo?.BusinessLicenseCode || '-' }}</div></div>
            <div class="row"><div class="label">营业执照名称</div><div class="value">{{ entry.paper.CompanyInfo?.BusinessLicenseName || '-' }}</div></div>
            <div class="row"><div class="label">营业执照有效期</div><div class="value">{{ entry.paper.CompanyInfo?.BusinessLicenseFrom || '-' }} ~ {{ entry.paper.CompanyInfo?.BusinessLicenseTo || '-' }}</div></div>
            <div class="row"><div class="label">法人姓名</div><div class="value">{{ entry.paper.CompanyInfo?.LawyerName || '-' }}</div></div>
            <div class="row"><div class="label">经营范围</div><div class="value">{{ entry.paper.CompanyInfo?.BusinessScope || '-' }}</div></div>
            <div class="row"><div class="label">注册地址</div><div class="value">{{ entry.paper.CompanyInfo?.RegisterAddress || '-' }}</div></div>
            <div class="row"><div class="label">注册资本</div><div class="value">{{ entry.paper.CompanyInfo?.RegisteredCapital ?? '-' }}</div></div>
            <div class="row"><div class="label">合同状态</div><div class="value">{{ entry.paper.CompanyInfo?.ContractStatus || '-' }}</div></div>
            <div class="row"><div class="label">备注</div><div class="value">{{ entry.paper.CompanyInfo?.Remarks || '-' }}</div></div>
          </div>
          <div class="thumbs">
            <div v-if="entry.paper.CompanyInfo?.BusinessLicensePhotoURL" class="thumb"><img :src="safeUrl(entry.paper.CompanyInfo?.BusinessLicensePhotoURL)" alt="营业执照"></div>
            <div v-if="entry.paper.CompanyInfo?.StoreHeadPhotoURL" class="thumb"><img :src="safeUrl(entry.paper.CompanyInfo?.StoreHeadPhotoURL)" alt="门头照片"></div>
            <div v-if="entry.paper.CompanyInfo?.StoreShopPhotoURL" class="thumb"><img :src="safeUrl(entry.paper.CompanyInfo?.StoreShopPhotoURL)" alt="店铺照片"></div>
            <div v-if="entry.paper.CompanyInfo?.StoreHallPhotoURL" class="thumb"><img :src="safeUrl(entry.paper.CompanyInfo?.StoreHallPhotoURL)" alt="大厅照片"></div>
            <div v-if="entry.paper.CompanyInfo?.StoreCashierPhotoURL" class="thumb"><img :src="safeUrl(entry.paper.CompanyInfo?.StoreCashierPhotoURL)" alt="收银台照片"></div>
            <template v-if="entry.paper.CompanyInfo?.OtherPhotoURL?.length">
              <div v-for="(p, i) in entry.paper.CompanyInfo?.OtherPhotoURL" :key="'other-'+i" class="thumb"><img :src="safeUrl(p)" :alt="'其他'+(i+1)"></div>
            </template>
            <div v-if="entry.paper.CompanyInfo?.ContractAttachmentURL" class="thumb"><img :src="safeUrl(entry.paper.CompanyInfo?.ContractAttachmentURL)" alt="合同附件"></div>
          </div>
        </div>

        <div v-if="entry.paper.LawyerInfo" class="subcard">
          <h4 class="subcard-title">法人信息</h4>
          <div class="detail-grid">
            <div class="row"><div class="label">证件类型</div><div class="value">{{ entry.paper.LawyerInfo?.LawyerCertType || '-' }}</div></div>
            <div class="row"><div class="label">证件号码</div><div class="value">{{ entry.paper.LawyerInfo?.LawyerCertNo || '-' }}</div></div>
            <div class="row"><div class="label">证件姓名</div><div class="value">{{ entry.paper.LawyerInfo?.CertificateName || '-' }}</div></div>
            <div class="row"><div class="label">证件有效期</div><div class="value">{{ entry.paper.LawyerInfo?.CertificateFrom || '-' }} ~ {{ entry.paper.LawyerInfo?.CertificateTo || '-' }}</div></div>
            <div class="row"><div class="label">联系电话</div><div class="value">{{ entry.paper.LawyerInfo?.LegalPersonPhone || '-' }}</div></div>
            <div class="row"><div class="label">国家/地区</div><div class="value">{{ entry.paper.LawyerInfo?.LawyerCountry || '-' }}</div></div>
            <div class="row"><div class="label">地址</div><div class="value">{{ entry.paper.LawyerInfo?.LawyerAddress || '-' }}</div></div>
          </div>
          <div class="thumbs">
            <div v-if="entry.paper.LawyerInfo?.LawyerCertPhotoFrontURL" class="thumb"><img :src="safeUrl(entry.paper.LawyerInfo?.LawyerCertPhotoFrontURL)" alt="法人证件正面"></div>
            <div v-if="entry.paper.LawyerInfo?.LawyerCertPhotoBackURL" class="thumb"><img :src="safeUrl(entry.paper.LawyerInfo?.LawyerCertPhotoBackURL)" alt="法人证件反面"></div>
          </div>
        </div>

        <div v-if="entry.paper.OpenAccountInfo" class="subcard">
          <h4 class="subcard-title">开户信息</h4>
          <div class="detail-grid">
            <div class="row"><div class="label">开户类型</div><div class="value">{{ entry.paper.OpenAccountInfo?.OpenAccountType || '-' }}</div></div>
            <div class="row"><div class="label">许可证账户名</div><div class="value">{{ entry.paper.OpenAccountInfo?.LicenceAccount || '-' }}</div></div>
            <div class="row"><div class="label">许可证账号</div><div class="value">{{ entry.paper.OpenAccountInfo?.LicenceAccountNo || '-' }}</div></div>
            <div class="row"><div class="label">开户行</div><div class="value">{{ entry.paper.OpenAccountInfo?.LicenceOpenBank || '-' }}</div></div>
            <div class="row"><div class="label">开户支行</div><div class="value">{{ entry.paper.OpenAccountInfo?.LicenceOpenSubBank || '-' }}</div></div>
          </div>
          <div class="thumbs">
            <div v-if="entry.paper.OpenAccountInfo?.OpeningLicenseAccountPhotoURL" class="thumb"><img :src="safeUrl(entry.paper.OpenAccountInfo?.OpeningLicenseAccountPhotoURL)" alt="开户许可证"></div>
          </div>
        </div>

        <div v-if="entry.paper.SettleAccountInfo" class="subcard">
          <h4 class="subcard-title">结算账户信息</h4>
          <div class="detail-grid">
            <div class="row"><div class="label">结算主体</div><div class="value">{{ entry.paper.SettleAccountInfo?.SettleTarget || '-' }}</div></div>
            <div class="row"><div class="label">账户类型</div><div class="value">{{ entry.paper.SettleAccountInfo?.SettleAccountType || '-' }}</div></div>
            <div class="row"><div class="label">账户名</div><div class="value">{{ entry.paper.SettleAccountInfo?.SettleAccount || '-' }}</div></div>
            <div class="row"><div class="label">账号</div><div class="value">{{ entry.paper.SettleAccountInfo?.SettleAccountNo || '-' }}</div></div>
            <div class="row"><div class="label">开户行</div><div class="value">{{ entry.paper.SettleAccountInfo?.OpenBank || '-' }}</div></div>
            <div class="row"><div class="label">开户支行</div><div class="value">{{ entry.paper.SettleAccountInfo?.OpenSubBank || '-' }}</div></div>
            <div class="row"><div class="label">联行号</div><div class="value">{{ entry.paper.SettleAccountInfo?.OpenBankCode || '-' }}</div></div>
            <div class="row"><div class="label">预留手机号</div><div class="value">{{ entry.paper.SettleAccountInfo?.OpenBankReservePhone || '-' }}</div></div>
            <div class="row"><div class="label">是否默认</div><div class="value">{{ entry.paper.SettleAccountInfo?.IsDefault || '-' }}</div></div>
            <div class="row"><div class="label">附言</div><div class="value">{{ entry.paper.SettleAccountInfo?.Postscript || '-' }}</div></div>
            <div class="row"><div class="label">摘要</div><div class="value">{{ entry.paper.SettleAccountInfo?.Summary || '-' }}</div></div>
            <div class="row"><div class="label">用途</div><div class="value">{{ entry.paper.SettleAccountInfo?.Purpose || '-' }}</div></div>
          </div>
          <div class="thumbs">
            <div v-if="entry.paper.SettleAccountInfo?.SettleCertFrontPhotoURL" class="thumb"><img :src="safeUrl(entry.paper.SettleAccountInfo?.SettleCertFrontPhotoURL)" alt="结算证件正面"></div>
            <div v-if="entry.paper.SettleAccountInfo?.SettleCertBackPhotoURL" class="thumb"><img :src="safeUrl(entry.paper.SettleAccountInfo?.SettleCertBackPhotoURL)" alt="结算证件反面"></div>
            <div v-if="entry.paper.SettleAccountInfo?.BankCardPhotoFrontURL" class="thumb"><img :src="safeUrl(entry.paper.SettleAccountInfo?.BankCardPhotoFrontURL)" alt="银行卡正面"></div>
            <div v-if="entry.paper.SettleAccountInfo?.BankCardPhotoBackURL" class="thumb"><img :src="safeUrl(entry.paper.SettleAccountInfo?.BankCardPhotoBackURL)" alt="银行卡反面"></div>
            <div v-if="entry.paper.SettleAccountInfo?.AccountIntentPhotoURL" class="thumb"><img :src="safeUrl(entry.paper.SettleAccountInfo?.AccountIntentPhotoURL)" alt="账户意愿书"></div>
            <div v-if="entry.paper.SettleAccountInfo?.WithdrawProofPhotoURL" class="thumb"><img :src="safeUrl(entry.paper.SettleAccountInfo?.WithdrawProofPhotoURL)" alt="提现证明"></div>
            <div v-if="entry.paper.SettleAccountInfo?.TransferApplyAttachmentURL" class="thumb"><img :src="safeUrl(entry.paper.SettleAccountInfo?.TransferApplyAttachmentURL)" alt="划款申请书"></div>
            <div v-if="entry.paper.SettleAccountInfo?.SettleAttachmentURL" class="thumb"><img :src="safeUrl(entry.paper.SettleAccountInfo?.SettleAttachmentURL)" alt="结算附件"></div>
            <div v-if="entry.paper.SettleAccountInfo?.SettleLicensePhotoURL" class="thumb"><img :src="safeUrl(entry.paper.SettleAccountInfo?.SettleLicensePhotoURL)" alt="结算许可证"></div>
          </div>
        </div>

        <div v-if="entry.paper.ControllerList?.length" class="subcard">
          <h4 class="subcard-title">受益人信息</h4>
          <div class="controller-list">
            <div v-for="(c, idx) in entry.paper.ControllerList" :key="idx" class="controller-item">
              <div class="detail-grid">
                <div class="row"><div class="label">姓名</div><div class="value">{{ c.ControllerName || '-' }}</div></div>
                <div class="row"><div class="label">类型</div><div class="value">{{ c.ControllerType || '-' }}</div></div>
                <div class="row"><div class="label">证件号</div><div class="value">{{ c.ControllerNo || '-' }}</div></div>
                <div class="row"><div class="label">有效期</div><div class="value">{{ c.ControllerFrom || '-' }} ~ {{ c.ControllerTo || '-' }}</div></div>
                <div class="row"><div class="label">国家/地区</div><div class="value">{{ c.ControllerCountry || '-' }}</div></div>
                <div class="row"><div class="label">地址</div><div class="value">{{ c.ControllerAddress || '-' }}</div></div>
              </div>
              <div class="thumbs">
                <div v-if="c.ControllerPhotoFrontURL" class="thumb"><img :src="safeUrl(c.ControllerPhotoFrontURL)" alt="证件正面"></div>
                <div v-if="c.ControllerPhotoBackURL" class="thumb"><img :src="safeUrl(c.ControllerPhotoBackURL)" alt="证件反面"></div>
              </div>
            </div>
          </div>
        </div>

        <div v-if="entry.paper.OtherInfo" class="subcard">
          <h4 class="subcard-title">其他信息</h4>
          <div class="detail-grid">
            <div class="row"><div class="label">微信渠道ID</div><div class="value">{{ entry.paper.OtherInfo?.WechatChannelId || '-' }}</div></div>
            <div class="row"><div class="label">支付宝渠道ID</div><div class="value">{{ entry.paper.OtherInfo?.AlipayChannelId || '-' }}</div></div>
            <div class="row"><div class="label">微信商户名</div><div class="value">{{ entry.paper.OtherInfo?.WechatMerchantName || '-' }}</div></div>
            <div class="row"><div class="label">支付宝商户名</div><div class="value">{{ entry.paper.OtherInfo?.AlipayMerchantName || '-' }}</div></div>
            <div class="row"><div class="label">服务电话</div><div class="value">{{ entry.paper.OtherInfo?.ServiceTel || '-' }}</div></div>
            <div class="row"><div class="label">ICP备案号</div><div class="value">{{ entry.paper.OtherInfo?.IcpRecordNo || '-' }}</div></div>
            <div class="row"><div class="label">网站地址</div><div class="value">{{ entry.paper.OtherInfo?.SiteUrl || '-' }}</div></div>
            <div class="row"><div class="label">网站/应用名称</div><div class="value">{{ entry.paper.OtherInfo?.WebsiteOrAppName || '-' }}</div></div>
            <div class="row"><div class="label">微信商户业务ID</div><div class="value">{{ entry.paper.OtherInfo?.WechatBusinessId || '-' }}</div></div>
            <div class="row"><div class="label">支付宝MCC</div><div class="value">{{ entry.paper.OtherInfo?.AlipayMcc || '-' }}</div></div>
            <div class="row"><div class="label">机构匹配名</div><div class="value">{{ entry.paper.OtherInfo?.AcqMatchName || '-' }}</div></div>
            <div class="row"><div class="label">银联简称</div><div class="value">{{ entry.paper.OtherInfo?.UnionShortName || '-' }}</div></div>
            <div class="row"><div class="label">网站首页</div><div class="value">{{ entry.paper.OtherInfo?.WebsiteHomePage || '-' }}</div></div>
            <div class="row"><div class="label">售后页面</div><div class="value">{{ entry.paper.OtherInfo?.WebsiteAfterSales || '-' }}</div></div>
            <div class="row"><div class="label">其他页面</div><div class="value">{{ entry.paper.OtherInfo?.WebsiteOthers || '-' }}</div></div>
            <div class="row"><div class="label">小程序名称</div><div class="value">{{ entry.paper.OtherInfo?.WxMiniAppName || '-' }}</div></div>
            <div class="row"><div class="label">公众号名称</div><div class="value">{{ entry.paper.OtherInfo?.WxPublicAccountName || '-' }}</div></div>
            <div class="row"><div class="label">小程序授权页</div><div class="value">{{ entry.paper.OtherInfo?.WxMiniAppAuthPage || '-' }}</div></div>
            <div class="row"><div class="label">小程序首页</div><div class="value">{{ entry.paper.OtherInfo?.WxMiniAppHomePage || '-' }}</div></div>
            <div class="row"><div class="label">小程序下单页</div><div class="value">{{ entry.paper.OtherInfo?.WxMiniAppOrderPage || '-' }}</div></div>
            <div class="row"><div class="label">公众号授权页</div><div class="value">{{ entry.paper.OtherInfo?.WxPublicAccountAuthPage || '-' }}</div></div>
            <div class="row"><div class="label">公众号首页</div><div class="value">{{ entry.paper.OtherInfo?.WxPublicAccountHomePage || '-' }}</div></div>
            <div class="row"><div class="label">公众号下单页</div><div class="value">{{ entry.paper.OtherInfo?.WxPublicAccountOrderPage || '-' }}</div></div>
            <div class="row"><div class="label">应用商店链接</div><div class="value">{{ entry.paper.OtherInfo?.AppStorePage || '-' }}</div></div>
            <div class="row"><div class="label">应用介绍视频</div><div class="value">{{ entry.paper.OtherInfo?.AppDescVideo || '-' }}</div></div>
            <div class="row"><div class="label">其他资料附件</div><div class="value">{{ entry.paper.OtherInfo?.OtherSheetAttachment || '-' }}</div></div>
          </div>
          <div class="thumbs">
            <template v-if="entry.paper.OtherInfo?.ScenarioPhoto?.length">
              <div v-for="(p, i) in entry.paper.OtherInfo?.ScenarioPhoto" :key="'sc-'+i" class="thumb"><img :src="safeUrl(p)" :alt="'场景'+(i+1)"></div>
            </template>
            <template v-if="entry.paper.OtherInfo?.HandheldPhotoForAccount?.length">
              <div v-for="(p, i) in entry.paper.OtherInfo?.HandheldPhotoForAccount" :key="'hh-'+i" class="thumb"><img :src="safeUrl(p)" :alt="'手持'+(i+1)"></div>
            </template>
            <template v-if="entry.paper.OtherInfo?.PayFlowchart?.length">
              <div v-for="(p, i) in entry.paper.OtherInfo?.PayFlowchart" :key="'flow-'+i" class="thumb"><img :src="safeUrl(p)" :alt="'支付流程'+(i+1)"></div>
            </template>
            <div v-if="entry.paper.OtherInfo?.IcpRecordPhoto" class="thumb"><img :src="safeUrl(entry.paper.OtherInfo?.IcpRecordPhoto)" alt="ICP备案照片"></div>
            <div v-if="entry.paper.OtherInfo?.PayFlowchartAttachment" class="thumb"><img :src="safeUrl(entry.paper.OtherInfo?.PayFlowchartAttachment)" alt="流程附件"></div>
            <div v-if="entry.paper.OtherInfo?.WithdrawAgreement" class="thumb"><img :src="safeUrl(entry.paper.OtherInfo?.WithdrawAgreement)" alt="提现协议"></div>
            <div v-if="entry.paper.OtherInfo?.OtherSheetAttachment" class="thumb"><img :src="safeUrl(entry.paper.OtherInfo?.OtherSheetAttachment)" alt="其他资料"></div>
            <template v-if="entry.paper.OtherInfo?.SpecialPermit?.length">
              <div v-for="(p, i) in entry.paper.OtherInfo?.SpecialPermit" :key="'sp-'+i" class="thumb"><img :src="safeUrl(p)" :alt="'专项许可'+(i+1)"></div>
            </template>
          </div>
        </div>
      </div>

      <!-- 营业资料（business）结构化展示 -->
      <div v-if="entry?.business?.length" class="subcards">
        <div v-for="(b, idx) in entry.business" :key="idx" class="subcard">
          <h4 class="subcard-title">支付业务：{{ b.BusinessName || b.BusinessCode }}</h4>
          <div class="detail-grid">
            <div class="row"><div class="label">业务名称</div><div class="value">{{ b.BusinessName || '-' }}</div></div>
            <div class="row"><div class="label">业务编码</div><div class="value">{{ b.BusinessCode }}</div></div>
            <div class="row"><div class="label">状态</div><div class="value">{{ b.State || '-' }}</div></div>
            <div class="row"><div class="label">说明</div><div class="value">{{ b.Msg || '-' }}</div></div>
            <div class="row"><div class="label">结算周期</div><div class="value">{{ b.SettleCycle || '-' }}</div></div>
            <div class="row"><div class="label">单笔限额</div><div class="value">{{ formatMoney(b.MinTxsAmount) }} ~ {{ formatMoney(b.MaxTxsAmount) }}</div></div>
            <div class="row"><div class="label">手续费范围</div><div class="value">{{ formatMoney(b.FeeMin) }} ~ {{ formatMoney(b.FeeMax) }}</div></div>
            <div class="row"><div class="label">退款支持</div><div class="value">{{ formatYesNo(b.RefundEnabled) }}</div></div>
            <div class="row"><div class="label">退款费率</div><div class="value">{{ formatPercent(b.RefundFeeRate, b.RefundFeePer) }}</div></div>
            <div class="row"><div class="label">信用卡支持</div><div class="value">{{ formatYesNo(b.CreditcardsEnabled) }}</div></div>
            <div class="row"><div class="label">原交易分账</div><div class="value">{{ formatYesNo(b.SplitOriTradeFee) }}</div></div>
          </div>
          <div v-if="b.Stage?.length" class="chips">
            <div class="chip-title">费率区间</div>
            <div class="chip-list">
              <span v-for="(s, i) in b.Stage" :key="'st-'+i" class="chip">费率 {{ s.FeeRate || '-' }}，单笔 {{ formatMoney(s.FeePer) }}，起额 {{ formatMoney(s.AmountFrom) }}</span>
            </div>
          </div>
          <div v-if="b.BankStage?.length" class="chips">
            <div class="chip-title">银行费率</div>
            <div class="chip-list">
              <span v-for="(bk, i) in b.BankStage" :key="'bk-'+i" class="chip">{{ bk.Bankcode }}：费率 {{ bk.FeeRate || '-' }} / 单笔 {{ formatMoney(bk.FeePer) }}</span>
            </div>
          </div>
          <div class="detail-grid">
            <div class="row"><div class="label">节假日类型</div><div class="value">{{ b.HolidayType || '-' }}</div></div>
            <div class="row"><div class="label">节假日费率</div><div class="value">{{ formatPercent(b.HolidayRate, b.HolidayPer) }}</div></div>
            <div class="row"><div class="label">税费类型</div><div class="value">{{ b.TaxFeeType || '-' }}</div></div>
            <div class="row"><div class="label">税费</div><div class="value">{{ formatPercent(b.TaxFeeRate, b.TaxFeePer) }}</div></div>
            <div class="row"><div class="label">渠道费类型</div><div class="value">{{ b.ChannelFeeType || '-' }}</div></div>
            <div class="row"><div class="label">渠道费</div><div class="value">{{ formatPercent(b.ChannelFeeRate, b.ChannelFeePer) }}</div></div>
          </div>
        </div>
      </div>
    </div>

    <!-- 下属门店列表 -->
    <div class="card table-container slide-up" style="animation-delay: 0.3s">
      <div class="table-header">
        <h3>下属门店</h3>
        <div class="table-actions">
          <button class="btn secondary" @click="loadStores">
            <span class="icon">🔄</span>
            刷新
          </button>
        </div>
      </div>

      <table class="table">
        <thead>
          <tr>
            <th>门店编码</th>
            <th>名称</th>
            <th>联系电话</th>
            <th>启用状态</th>
            <th>创建时间</th>
            <th>操作</th>
          </tr>
        </thead>
        <tbody>
          <tr v-if="storesLoading" class="loading-row">
            <td colspan="6" class="loading">
              <div class="spinner"></div>
              加载中...
            </td>
          </tr>
          <tr v-else-if="stores.length === 0" class="empty-row">
            <td colspan="6" class="empty">暂无门店</td>
          </tr>
          <tr v-else v-for="s in stores" :key="s.id" class="table-row">
            <td>{{ s.storeCode || '-' }}</td>
            <td>{{ s.name || '-' }}</td>
            <td>{{ s.contactPhone || '-' }}</td>
            <td>
              <span class="badge" :class="enableBadge(s.enableStatus)">{{ enableText(s.enableStatus) }}</span>
            </td>
            <td>{{ formatDate(s.creationTime) }}</td>
            <td>
              <router-link class="btn small" :to="`/stores/detail/${s.id}`">详情</router-link>
            </td>
          </tr>
        </tbody>
      </table>
    </div>
  </div>
</template>

<script setup lang="ts">
import { onMounted, ref } from 'vue'
import { useRoute } from 'vue-router'
import { OrganizationService, type MerchantResponse } from '../services/organization'
import { StoreService, type StoreResponse } from '../services/store'
import { isSuccess } from '../services/types'

const route = useRoute()
const id = String(route.params.id || '')
const loading = ref(false)
const merchant = ref<MerchantResponse | null>(null)
const storesLoading = ref(false)
const stores = ref<StoreResponse[]>([])
const entryLoading = ref(false)
const entry = ref<MerchantResponse | null>(null)
const pageSize = 5

/**
 * 文件级注释：
 * 商户详情页面，展示基础信息、进件资料（paper/business JSON）以及下属门店列表。
 * 仅在 H5 项目中进行改造；前端所有接口调用以返回值 code === 0 判定成功。
 */

/**
 * 格式化时间为中文本地字符串
 * @param v 原始时间字符串（ISO/可解析格式）
 * @returns 格式化后的中文本地时间，无法解析则原样返回或返回'-'
 * @throws 无（内部 try-catch 防御）
 */
function formatDate(v?: string) {
  if (!v) return '-'
  try { return new Date(v).toLocaleString('zh-CN') } catch { return v }
}
function auditText(s?: number) {
  /**
   * 审核状态文案
   * @param s 审核状态代码：1待审核、2通过、3未通过
   * @returns 中文描述字符串
   * @throws 无（纯映射）
   */
  if (s === 2) return '审核通过'
  if (s === 3) return '审核未通过'
  if (s === 1) return '待审核'
  return '未知'
}
function accountText(s?: number) {
  /**
   * 账户开通状态文案
   * @param s 账户状态代码：1已开通、0未开通
   * @returns 中文描述字符串
   * @throws 无（纯映射）
   */
  if (s === 1) return '已开通'
  if (s === 0) return '未开通'
  return '未知'
}

/**
 * 接单能力文案
 * @param s 可接单标记（0/1/undefined）
 * @returns 中文文案
 */
function acceptOrderText(s?: number) {
  if (s === 1) return '可接单'
  if (s === 0) return '不可接单'
  return '未知'
}

function enableText(s?: number) {
  /**
   * 启用状态文本
   * @param s 启用状态：1启用、0禁用
   * @returns 中文描述字符串
   * @throws 无（纯映射）
   */
  if (s === 1) return '启用'
  if (s === 0) return '禁用'
  return '未知'
}
function enableBadge(s?: number) {
  /**
   * 启用状态徽章样式类名
   * @param s 启用状态：1启用、0禁用
   * @returns 类名字符串：'active' 或 'inactive'
   * @throws 无（纯映射）
   */
  return s === 1 ? 'active' : 'inactive'
}

/**
 * 加载商户基础详情（平台后端接口）
 * @returns void 无返回值，直接更新 merchant 响应式数据
 * @throws 网络或服务端异常会被捕获并在控制台输出
 */
async function loadDetail() {
  loading.value = true
  try {
    const res = await OrganizationService.getMerchantDetail(id)
    if (isSuccess(res)) {
      merchant.value = res.data || null
    } else {
      merchant.value = null
      console.warn('获取商户详情失败:', res?.message)
    }
  } catch (e) {
    console.error('接口异常:', e)
  } finally {
    loading.value = false
  }
}

/**
 * 加载商户进件信息详情（GetMerchantEntryDetailAsync）
 * @returns void 无返回值，直接更新 entry 响应式数据
 * @throws 网络或服务端异常会被捕获并在控制台输出
 */
async function loadEntry() {
  entryLoading.value = true
  try {
    const res = await OrganizationService.getMerchantEntryDetail(id)
    if (isSuccess(res)) {
      // 处理大小写不一致的字段命名（PascalCase/CamelCase）并进行深度包裹
      const data: any = res.data || null
      if (data) {
        const rawPaper = data.paper ?? data.Paper
        const rawBusiness = data.business ?? data.Business
        data.paper = wrapCase(rawPaper)
        data.business = wrapCase(rawBusiness)
      }
      entry.value = data
    } else {
      entry.value = null
      console.warn('获取商户进件详情失败:', res?.message)
    }
  } catch (e) {
    console.error('接口异常:', e)
  } finally {
    entryLoading.value = false
  }
}

/**
 * 加载商户下属门店列表
 * @returns void 无返回值，直接更新 stores 响应式数据
 * @throws 网络或服务端异常会被捕获并在控制台输出
 */
async function loadStores() {
  storesLoading.value = true
  try {
    const res = await StoreService.getStoreList(1, pageSize, '', id)
    if (isSuccess(res) && res.data) {
      stores.value = res.data.data || []
    } else {
      stores.value = []
      console.warn('获取门店列表失败:', res?.message)
    }
  } catch (e) {
    console.error('接口异常:', e)
  } finally {
    storesLoading.value = false
  }
}

/**
 * 将 0/1/布尔/数字/字符串 映射为“是/否”
 * @param v 原始值（0/1/true/false/数字/字符串）
 * @returns 中文“是/否”或“-”
 * @throws 无异常（纯映射）
 */
function formatYesNo(v: any): string {
  if (v === null || v === undefined || v === '') return '-'
  const n = typeof v === 'string' ? Number(v) : v
  return (n === 1 || n === true) ? '是' : '否'
}

/**
 * 规范化图片/文件 URL
 * @param v 输入 URL 或文件 ID
 * @returns 可供 img 使用的 URL（原样返回）
 * @throws 无异常（纯字符串处理）
 */
function safeUrl(v?: string): string {
  if (!v) return ''
  return String(v)
}

/**
 * 格式化费率（百分比或固定额）
 * @param rate 百分比字符串，如 "0.38%" 或 "0.38"
 * @param per 固定额（分/元，后端可能为分）
 * @returns 组合文案，如 "0.38% / 单笔0.02"
 * @throws 无异常（纯字符串组合）
 */
function formatPercent(rate?: string, per?: number): string {
  const r = rate ? `${rate}%`.replace('%%', '%') : '-'
  const p = per !== undefined && per !== null ? `单笔${formatMoney(per)}` : ''
  return [r, p].filter(Boolean).join(' / ')
}

/**
 * 格式化金额（数字）为友好字符串
 * @param v 金额或数值
 * @returns 保留两位或整数的文本；空值为 "-"
 * @throws 无异常
 */
/**
 * 函数级注释：格式化金额（分）为人民币元显示
 * @param v 金额（分，number 或可转为 number）
 * @returns 字符串，形如 `¥123.45`；空值或非法值返回 "-"
 * @throws 无显式异常（内部做 NaN 防御）
 */
function formatMoney(v?: number): string {
  if (v === null || v === undefined) return '-'
  const n = Number(v)
  if (Number.isNaN(n)) return '-'
  return `¥${(n / 100).toFixed(2)}`
}

/**
 * 将对象或可解析 JSON 的字符串格式化为缩进显示
 * @param v 任意值（对象、数组、字符串等）
 * @returns 友好的 JSON 字符串；空值返回'-'
 */
function formatJson(v: any): string {
  if (v === null || v === undefined) return '-'
  try {
    if (typeof v === 'string') {
      // 尝试解析字符串为 JSON
      try { return JSON.stringify(JSON.parse(v), null, 2) } catch { /* 非 JSON 字符串 */ }
      return v
    }
    return JSON.stringify(v, null, 2)
  } catch {
    return String(v)
  }
}

/**
 * 深度包裹对象/数组，提供属性大小写回退（PascalCase -> camelCase）
 * @param obj 原始对象或数组
 * @returns 具有属性访问回退能力的代理对象/数组；非对象原样返回
 * @throws 无异常（纯数据包装）
 */
function wrapCase(obj: any): any {
  if (Array.isArray(obj)) {
    return obj.map((it) => wrapCase(it))
  }
  if (obj && typeof obj === 'object') {
    return new Proxy(obj, {
      get(target: any, prop: any, receiver) {
        if (typeof prop !== 'string') return Reflect.get(target, prop, receiver)
        const val = prop in target ? target[prop] : target[prop.charAt(0).toLowerCase() + prop.slice(1)]
        // 对嵌套对象继续包裹，确保深层字段也有大小写回退
        return wrapCase(val)
      },
    })
  }
  return obj
}

onMounted(() => {
  loadDetail()
  loadEntry()
  loadStores()
})
</script>

<style scoped>
.detail-grid { display: grid; grid-template-columns: 200px 1fr; gap: 12px; }
.row { display: contents; }
.label { color: var(--text-secondary); }
.value { color: var(--text); font-weight: 500; }
.loading-state, .empty-state { text-align: center; padding: var(--space-6); color: var(--text-secondary); }
/* 表格样式复用列表页风格 */
.card-header { margin-bottom: var(--space-3); }
.card-subtitle { color: var(--text-secondary); font-size: 12px; }
.json-grid { display: grid; grid-template-columns: 1fr 1fr; gap: var(--space-4); margin-top: var(--space-3); }
.json-col { display: flex; flex-direction: column; }
.json-title { font-weight: 600; margin-bottom: var(--space-2); }
.json-view { background: var(--bg-light); border: 1px solid var(--border); border-radius: var(--radius); padding: var(--space-3); white-space: pre-wrap; font-family: ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, "Liberation Mono", "Courier New", monospace; font-size: 12px; line-height: 1.6; }
.subcards { display: grid; grid-template-columns: 1fr; gap: var(--space-4); margin-top: var(--space-3); }
.subcard { border: 1px solid var(--border); border-radius: var(--radius); padding: var(--space-3); background: var(--bg-light); }
.subcard-title { font-weight: 600; margin-bottom: var(--space-2); }
.thumbs { display: flex; flex-wrap: wrap; gap: 8px; margin-top: 8px; }
.thumb { width: 120px; height: 80px; border: 1px solid var(--border); border-radius: var(--radius-sm); overflow: hidden; background: #fff; }
.thumb img { width: 100%; height: 100%; object-fit: cover; }
.chips { margin-top: var(--space-2); }
.chip-title { color: var(--text-secondary); margin-bottom: 6px; }
.chip-list { display: flex; flex-wrap: wrap; gap: 8px; }
.chip { background: var(--bg-secondary); border: 1px solid var(--border); border-radius: 999px; padding: 4px 10px; font-size: 12px; color: var(--text); }
.controller-list { display: grid; grid-template-columns: 1fr; gap: 12px; }
.controller-item { border-top: 1px dashed var(--border); padding-top: 10px; }
.table { width: 100%; border-collapse: collapse; }
.table th, .table td { padding: 12px; border-bottom: 1px solid var(--border); }
.badge { padding: 2px 8px; border-radius: var(--radius); font-size: var(--text-sm); }
.badge.active { background: var(--primary-50); color: var(--primary-700); }
.badge.inactive { background: var(--bg-secondary); color: var(--text-secondary); }
.table-container { overflow-x: auto; }
.table-header { display:flex; align-items:center; justify-content:space-between; padding: 8px 12px; }
.table-actions { display:flex; gap: 8px; }
.spinner { width: 16px; height: 16px; border: 2px solid var(--border); border-top-color: var(--primary-600); border-radius: 50%; display:inline-block; animation: spin 0.8s linear infinite; margin-right: 8px; }
@keyframes spin { to { transform: rotate(360deg); } }
</style>
